package com.minsf.rpc.bootstrap;

/**
 * @Description
 * @Author minify
 * @Date 2024/4/1 22:00
 * @Project sf-rpc
 */

import com.minsf.rpc.RpcApplication;
import com.minsf.rpc.config.RegistryConfig;
import com.minsf.rpc.config.RpcConfig;
import com.minsf.rpc.model.ServiceMetaInfo;
import com.minsf.rpc.model.ServiceRegisterInfo;
import com.minsf.rpc.registry.LocalRegistry;
import com.minsf.rpc.registry.Registry;
import com.minsf.rpc.registry.RegistryFactory;
import com.minsf.rpc.server.tcp.VertxTcpServer;

import java.util.List;

/**
 * 服务提供者初始化
 */
public class ProviderBootstrap {

    public static void init(List<ServiceRegisterInfo<?>> serviceRegisterInfoList) {
        // RPC 框架初始化（配置和注册中心）
        RpcApplication.init();

        // 全局配置
        RpcConfig rpcConfig = RpcApplication.getRpcConfig();

        for (ServiceRegisterInfo<?> serviceRegisterInfo : serviceRegisterInfoList) {

            String serviceName = serviceRegisterInfo.getServiceName();
            Class<?> implClass = serviceRegisterInfo.getImplClass();

            // 注册中心
            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());

            // 本地注册
            LocalRegistry.registry(serviceName, implClass);

            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServicePort(rpcConfig.getServerPort());
            serviceMetaInfo.setServiceVersion(rpcConfig.getVersion());
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());

            try {
                registry.register(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException(serviceName + "服务注册失败", e);
            }
        }

        // 启动服务器
        VertxTcpServer vertxTcpServer = new VertxTcpServer();
        vertxTcpServer.doStart(rpcConfig.getServerPort());
    }
}
